<template>
  <div class="alerts-container">
    <el-card class="alerts-card">
      <template #header>
        <div class="card-header">
          <span>告警管理</span>
          <div class="header-actions">
            <el-select v-model="statusFilter" placeholder="状态筛选" clearable size="small">
              <el-option label="全部" value=""></el-option>
              <el-option label="未处理" value="pending"></el-option>
              <el-option label="已确认" value="confirmed"></el-option>
              <el-option label="已解决" value="resolved"></el-option>
              <el-option label="已忽略" value="ignored"></el-option>
            </el-select>
            <el-select v-model="typeFilter" placeholder="类型筛选" clearable size="small">
              <el-option label="全部" value=""></el-option>
              <el-option label="闯红灯" value="red_light"></el-option>
              <el-option label="逆行" value="wrong_way"></el-option>
              <el-option label="超速" value="speeding"></el-option>
              <el-option label="违停" value="illegal_parking"></el-option>
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              style="width: 240px;"
              @change="handleDateRangeChange"
            />
          </div>
        </div>
      </template>

      <div class="alerts-table-container">
        <el-table
          v-loading="loading"
          :data="filteredAlerts"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="id" label="告警ID" width="80" align="center"></el-table-column>
          <el-table-column prop="type" label="告警类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getAlertTypeTag(scope.row.type)">{{ getAlertTypeText(scope.row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="camera_id" label="摄像头ID" width="100" align="center"></el-table-column>
          <el-table-column prop="camera_name" label="摄像头名称" width="150"></el-table-column>
          <el-table-column prop="timestamp" label="发生时间" width="180" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="发生地点" min-width="120"></el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="image_url" label="告警图片" width="100" align="center">
            <template #default="scope">
              <el-image
                v-if="scope.row.image_url"
                :src="getImageUrl(scope.row.image_url)"
                :preview-src-list="[getImageUrl(scope.row.image_url)]"
                style="width: 80px; height: 45px;"
                fit="cover"
              />
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleAlertDetail(scope.row)"
                v-if="scope.row.status === 'pending'"
              >
                处理
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleAlertDetail(scope.row)"
                v-else
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="table-footer">
        <div class="batch-operations">
          <el-button
            type="warning"
            size="small"
            @click="handleBatchConfirm"
            :disabled="selectedAlerts.length === 0"
          >
            批量确认
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="handleBatchResolve"
            :disabled="selectedAlerts.length === 0"
          >
            批量解决
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleBatchIgnore"
            :disabled="selectedAlerts.length === 0"
          >
            批量忽略
          </el-button>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredAlerts.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 告警详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="告警详情"
      width="800px"
      :before-close="handleDialogClose"
    >
      <div class="alert-detail">
        <div class="detail-header">
          <div class="detail-info">
            <h3>{{ selectedAlert ? getAlertTypeText(selectedAlert.type) : '' }}</h3>
            <div class="detail-meta">
              <span class="meta-item">告警ID: {{ selectedAlert?.id }}</span>
              <span class="meta-item">时间: {{ selectedAlert ? formatDateTime(selectedAlert.timestamp) : '' }}</span>
              <span class="meta-item">
                状态: <el-tag :type="selectedAlert ? getStatusTag(selectedAlert.status) : ''">
                  {{ selectedAlert ? getStatusText(selectedAlert.status) : '' }}
                </el-tag>
              </span>
            </div>
          </div>
        </div>

        <div class="detail-content">
          <div class="content-section">
            <h4>告警信息</h4>
            <el-descriptions border :column="1" size="small">
              <el-descriptions-item label="摄像头">
                {{ selectedAlert?.camera_name }} (ID: {{ selectedAlert?.camera_id }})
              </el-descriptions-item>
              <el-descriptions-item label="发生地点">{{ selectedAlert?.location }}</el-descriptions-item>
              <el-descriptions-item label="违规对象">{{ selectedAlert?.target || '未知' }}</el-descriptions-item>
              <el-descriptions-item label="置信度">{{ selectedAlert?.confidence ? `${selectedAlert.confidence}%` : '未知' }}</el-descriptions-item>
              <el-descriptions-item label="备注">{{ selectedAlert?.note || '无' }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="content-section">
            <h4>告警图片</h4>
            <div class="alert-image">
              <el-image
                v-if="selectedAlert?.image_url"
                :src="getImageUrl(selectedAlert.image_url)"
                fit="contain"
                style="max-width: 100%; max-height: 400px;"
              />
              <p v-else>暂无告警图片</p>
            </div>
          </div>

          <div class="content-section" v-if="selectedAlert?.status === 'pending'">
            <h4>处理告警</h4>
            <div class="alert-actions">
              <el-input
                v-model="alertNote"
                type="textarea"
                :rows="3"
                placeholder="请输入处理备注"
              />
              <div class="action-buttons">
                <el-button type="primary" @click="confirmAlert">确认告警</el-button>
                <el-button type="success" @click="resolveAlert">标记已解决</el-button>
                <el-button type="danger" @click="ignoreAlert">忽略告警</el-button>
              </div>
            </div>
          </div>

          <div class="content-section" v-else-if="selectedAlert?.processing_history">
            <h4>处理历史</h4>
            <el-timeline>
              <el-timeline-item
                v-for="(record, index) in selectedAlert.processing_history"
                :key="index"
                :timestamp="formatDateTime(record.timestamp)"
              >
                <div class="timeline-content">
                  <strong>{{ record.action }}</strong>
                  <p v-if="record.note">{{ record.note }}</p>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '../api/apiService'

export default {
  name: 'Alerts',
  setup() {
    // 状态
    const loading = ref(false)
    const alerts = ref([])
    const selectedAlerts = ref([])
    const selectedAlert = ref(null)
    const detailDialogVisible = ref(false)
    const alertNote = ref('')
    
    // 筛选条件
    const statusFilter = ref('')
    const typeFilter = ref('')
    const dateRange = ref([])
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(20)

    // 获取告警列表
    const fetchAlerts = async () => {
      loading.value = true
      try {
        const response = await api.alerts.getAlerts()
        alerts.value = response.data || []
      } catch (error) {
        ElMessage.error('获取告警列表失败')
        // 使用模拟数据
        alerts.value = generateMockAlerts()
      } finally {
        loading.value = false
      }
    }

    // 生成模拟告警数据
    const generateMockAlerts = () => {
      const types = ['red_light', 'wrong_way', 'speeding', 'illegal_parking']
      const statuses = ['pending', 'confirmed', 'resolved', 'ignored']
      const cameras = [
        { id: 1, name: '东门摄像头' },
        { id: 2, name: '南门摄像头' },
        { id: 3, name: '十字路口摄像头' },
        { id: 4, name: '高速入口摄像头' }
      ]
      
      const mockAlerts = []
      for (let i = 1; i <= 50; i++) {
        const type = types[Math.floor(Math.random() * types.length)]
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        const camera = cameras[Math.floor(Math.random() * cameras.length)]
        const timestamp = new Date(Date.now() - Math.floor(Math.random() * 7 * 24 * 60 * 60 * 1000))
        
        mockAlerts.push({
          id: i,
          type,
          camera_id: camera.id,
          camera_name: camera.name,
          timestamp: timestamp.toISOString(),
          location: `${camera.name}附近`,
          status,
          image_url: `/mock/images/alert_${i}.jpg`,
          confidence: Math.floor(Math.random() * 30) + 70,
          target: type === 'red_light' ? '车辆' : 
                  type === 'wrong_way' ? '车辆' : 
                  type === 'speeding' ? '车辆' : '车辆',
          note: status !== 'pending' ? '已处理' : '',
          processing_history: status !== 'pending' ? [{
            action: status === 'confirmed' ? '确认告警' : 
                    status === 'resolved' ? '标记已解决' : '忽略告警',
            timestamp: new Date(timestamp.getTime() + Math.random() * 3600000).toISOString(),
            note: '系统自动处理'
          }] : []
        })
      }
      
      return mockAlerts.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
    }

    // 过滤后的告警列表
    const filteredAlerts = computed(() => {
      let result = [...alerts.value]
      
      // 状态筛选
      if (statusFilter.value) {
        result = result.filter(alert => alert.status === statusFilter.value)
      }
      
      // 类型筛选
      if (typeFilter.value) {
        result = result.filter(alert => alert.type === typeFilter.value)
      }
      
      // 日期筛选
      if (dateRange.value && dateRange.value.length === 2) {
        const startDate = new Date(dateRange.value[0])
        const endDate = new Date(dateRange.value[1])
        endDate.setHours(23, 59, 59, 999)
        
        result = result.filter(alert => {
          const alertDate = new Date(alert.timestamp)
          return alertDate >= startDate && alertDate <= endDate
        })
      }
      
      return result
    })

    // 处理日期范围变化
    const handleDateRangeChange = () => {
      currentPage.value = 1
    }

    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedAlerts.value = selection
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (current) => {
      currentPage.value = current
    }

    // 告警类型标签颜色
    const getAlertTypeTag = (type) => {
      const tagMap = {
        red_light: 'danger',
        wrong_way: 'warning',
        speeding: 'primary',
        illegal_parking: 'info'
      }
      return tagMap[type] || 'default'
    }

    // 告警类型文本
    const getAlertTypeText = (type) => {
      const textMap = {
        red_light: '闯红灯',
        wrong_way: '逆行',
        speeding: '超速',
        illegal_parking: '违停'
      }
      return textMap[type] || '未知'
    }

    // 状态标签颜色
    const getStatusTag = (status) => {
      const tagMap = {
        pending: 'danger',
        confirmed: 'warning',
        resolved: 'success',
        ignored: 'info'
      }
      return tagMap[status] || 'default'
    }

    // 状态文本
    const getStatusText = (status) => {
      const textMap = {
        pending: '未处理',
        confirmed: '已确认',
        resolved: '已解决',
        ignored: '已忽略'
      }
      return textMap[status] || '未知'
    }

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }

    // 获取图片URL
    const getImageUrl = (url) => {
      // 这里可以根据实际情况处理图片URL
      return url.startsWith('http') ? url : `http://localhost:5001${url}`
    }

    // 处理告警详情
    const handleAlertDetail = (alert) => {
      selectedAlert.value = { ...alert }
      alertNote.value = ''
      detailDialogVisible.value = true
    }

    // 关闭对话框
    const handleDialogClose = () => {
      detailDialogVisible.value = false
      selectedAlert.value = null
      alertNote.value = ''
    }

    // 更新告警状态
    const updateAlert = async (alertId, status, note) => {
      try {
        await api.alerts.updateAlertStatus(alertId, status, note)
        ElMessage.success('操作成功')
        // 更新本地数据
        const index = alerts.value.findIndex(a => a.id === alertId)
        if (index !== -1) {
          alerts.value[index].status = status
          alerts.value[index].note = note
          if (!alerts.value[index].processing_history) {
            alerts.value[index].processing_history = []
          }
          alerts.value[index].processing_history.push({
            action: status === 'confirmed' ? '确认告警' : 
                    status === 'resolved' ? '标记已解决' : '忽略告警',
            timestamp: new Date().toISOString(),
            note: note
          })
        }
        handleDialogClose()
      } catch (error) {
        ElMessage.error('操作失败')
        // 模拟成功，直接更新本地数据
        const index = alerts.value.findIndex(a => a.id === alertId)
        if (index !== -1) {
          alerts.value[index].status = status
          alerts.value[index].note = note
          if (!alerts.value[index].processing_history) {
            alerts.value[index].processing_history = []
          }
          alerts.value[index].processing_history.push({
            action: status === 'confirmed' ? '确认告警' : 
                    status === 'resolved' ? '标记已解决' : '忽略告警',
            timestamp: new Date().toISOString(),
            note: note
          })
        }
        ElMessage.success('操作成功')
        handleDialogClose()
      }
    }

    // 确认告警
    const confirmAlert = () => {
      if (!selectedAlert.value) return
      updateAlert(selectedAlert.value.id, 'confirmed', alertNote.value)
    }

    // 解决告警
    const resolveAlert = () => {
      if (!selectedAlert.value) return
      updateAlert(selectedAlert.value.id, 'resolved', alertNote.value)
    }

    // 忽略告警
    const ignoreAlert = () => {
      if (!selectedAlert.value) return
      updateAlert(selectedAlert.value.id, 'ignored', alertNote.value)
    }

    // 批量操作
    const handleBatchConfirm = () => {
      if (selectedAlerts.value.length === 0) return
      selectedAlerts.value.forEach(alert => {
        updateAlert(alert.id, 'confirmed', '批量确认')
      })
      selectedAlerts.value = []
    }

    const handleBatchResolve = () => {
      if (selectedAlerts.value.length === 0) return
      selectedAlerts.value.forEach(alert => {
        updateAlert(alert.id, 'resolved', '批量解决')
      })
      selectedAlerts.value = []
    }

    const handleBatchIgnore = () => {
      if (selectedAlerts.value.length === 0) return
      selectedAlerts.value.forEach(alert => {
        updateAlert(alert.id, 'ignored', '批量忽略')
      })
      selectedAlerts.value = []
    }

    // 初始化
    onMounted(() => {
      fetchAlerts()
    })

    return {
      loading,
      alerts,
      filteredAlerts,
      selectedAlerts,
      selectedAlert,
      detailDialogVisible,
      alertNote,
      statusFilter,
      typeFilter,
      dateRange,
      currentPage,
      pageSize,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleDateRangeChange,
      getAlertTypeTag,
      getAlertTypeText,
      getStatusTag,
      getStatusText,
      formatDateTime,
      getImageUrl,
      handleAlertDetail,
      handleDialogClose,
      confirmAlert,
      resolveAlert,
      ignoreAlert,
      handleBatchConfirm,
      handleBatchResolve,
      handleBatchIgnore
    }
  }
}
</script>

<style scoped>
.alerts-container {
  padding: 20px;
}

.alerts-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.alerts-table-container {
  margin: 20px 0;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.batch-operations {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 10px;
}

/* 告警详情样式 */
.alert-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.detail-info h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.detail-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  color: #606266;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.content-section {
  margin-bottom: 25px;
}

.content-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.alert-image {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.alert-actions {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.timeline-content {
  color: #606266;
}

.timeline-content strong {
  color: #303133;
}
</style>